package com.nd.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nd.common.result.ResultUtils;
import com.nd.common.utils.EmptyUtils;
import com.nd.entity.Users;
import com.nd.service.IUsersService;
import org.apache.tomcat.util.http.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 *  用户的接口测试
 * @author liruirui
 * @since 2024-12-25
 */
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    IUsersService service;

    /**
     * 分页查询
     * @return
     */
    @GetMapping("/")
    public Object getList(Integer page, Integer limit){
        Page p = new Page(page, limit);
        IPage iPage = service.page(p);
        int total = (int)iPage.getTotal();  //总数
        List records = iPage.getRecords();  //当前页数据

        return ResultUtils.returnSuccessLayui(records,total);
    }

    /**
     * 根据id查询单个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Object getById(@PathVariable("id")Integer id){
        return service.getById(id);
    }

    @PostMapping("/login")
    public Object login(@RequestBody  Users users, HttpSession session){
        QueryWrapper qw = new QueryWrapper();
        qw.eq("uname",users.getUname());
        qw.eq("password",users.getPassword());
        Users one = service.getOne(qw);
        if (EmptyUtils.isNotEmpty(one))
        {
            session.setAttribute("userName",one.getUname());
            return ResultUtils.returnSuccess();
        }
        return ResultUtils.returnFail("用户或密码错误");
    }
    /**
     * 根据id删除单个
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Object del(@PathVariable("id")Integer id){
        if(service.removeById(id)){
            return ResultUtils.returnSuccess();
        }else{
            return ResultUtils.returnFail("删除失败");
        }
    }


    /**
     * 添加
     * @param users
     * @return
     */
    @PostMapping("/")
    public Object add(@RequestBody Users users){
        if(service.save(users)){
            return ResultUtils.returnSuccess();
        }else{
            return ResultUtils.returnFail("添加失败");
        }
    }



    /**
     * 修改
     * @param users
     * @return
     */
    @PutMapping("/")
    public Object update(@RequestBody Users users){
        if(service.updateById(users)){
            return ResultUtils.returnSuccess();
        }else{
            return ResultUtils.returnFail("修改失败");
        }
    }



}